<?php
class Projects extends CI_Controller {
	
	private static $results_per_page = 10;
	private $terms = array (); // default empty search terms array
	

	function __construct() {
		// load controller parent
		parent::__construct ();
		$this->results_per_page = self::$results_per_page;
		$this->load->model ( 'ProjectsM' );
		$this->load->model ( 'Mycommon' );
		
		$this->load->helper ( array ('form', 'url' ) );
        //Biblioteka za validiraneto
		
		//$this->output->enable_profiler(TRUE);
		//biblioteka za proverka dali e lognat user-a
		$this->load->library('tank_auth');
		
	//tova e proverka dali e lognat potrebitelja	
	if (!$this->tank_auth->is_logged_in()) {
			redirect('/auth/login/');
		}	
	}
	
	function index() {
		
		$this->search ();
	}
	
	/**
	 *
	 * Here goes your function description
	 *
	 */
	function search() {
		
		foreach ( $_POST as $key => $value ) {
//			echo $key . " " . "=" . " " . $value;
//			echo "<BR>";
		}
		if (! isset ( $_POST ['submit'] )) {
			
			// reset the search terms ако сме дошли на страницата директно т.е. не е натиснат бутона submit
//			$this->session->unset_userdata ( 's_category' );
			$this->session->unset_userdata ( 's_title' );
//			$this->session->unset_userdata ( 's_promotion' );
	}
		

//		$this->terms ['s_category'] = $this->input->post ( 's_category' );
		$this->terms ['s_title'] = $this->input->post ( 's_title' );
//		$this->terms ['s_promotion'] = $this->input->post ( 's_promotion' );
		
		$this->session->set_userdata ( $this->terms );
//		if ($this->input->post ( 's_category' )==5)
//		    $this->session->unset_userdata('s_category');
		redirect ( 'admin/projects/view' );
	
		//			}
	

	}
	
	function view($page=null) {
		
		$this->load->library ( 'pagination' );
		if (is_null($page))
			$offset = $this->uri->segment ( 4, 0 );
		else
		    $offset = $page;
				
		$total = $this->ProjectsM->count_all ();
		$data ['projects'] = $this->ProjectsM->get_all ( $this->results_per_page, $offset );
		
		$data ['total_rows'] = $total;
		
		$config ['base_url'] = site_url(). '/admin/projects/view';//base_url () . 'index.php/admin/products/view';
		$config ['total_rows'] = $total;
		$config ['per_page'] = $this->results_per_page;
		$config ['uri_segment'] = 4;
		$config ['num_links'] = 3;
		
		$this->pagination->initialize ( $config );
		
		$data ['page_links'] = $this->pagination->create_links ();

		$data ['s_title'] = $this->session->userdata ( 's_title' );
//		$data ['s_promotion'] = $this->session->userdata ( 's_promotion' );
		$data ['offset'] = $offset;
//		$data ['categories'] = $this->Mycommon->getCategoryAsSelect ( $this->session->userdata ( 's_category' ) );
		//print_r ( $this->db->last_query () );
		// application_view is our results page
		

		$data ['numusers'] = 11; //$this->Users_model->getNumUsers();
		$data ['title'] = 'Displaying user data';
		$data ['header'] = 'User List';
		$data ['currentPage']= floor(($offset/$config['per_page']) + 1);   
  
		$data ['current_dein']='projects';
		$this->load->view ( 'admin/header_view', $data );
		$this->load->view ( 'admin/admin_projects_list_view', $data );
		$this->load->view ( 'admin/footer_view', $data );
	
		//		$this->load->view ( 'application_view', $data );
	

	}
	
	
	
	function edit($id = null) {
		//Ako e podadeno ID shte redaktirame
	    $this->session->unset_userdata('new_images');
	    
		
		
		if (isset ( $id )) {
			$rows = $this->ProjectsM->getProjectsWhere ( "id", $id );
			$data ['project'] = $rows [0];
			$data ['numusers'] = 11; //$this->Users_model->getNumUsers();
			$data ['title'] = 'Displaying user data';
			$data ['header'] = 'User List';
			$data ['projectId'] = $id;
			$data ['images'] = $this->ProjectsM->get_images($id);
//			$data ['categories'] = $this->Mycommon->getCategoryAsSelect ( $rows[0]['category']);
			//		// load 'users_view' view
		}
		else{
			$data=array();
//			$data ['categories'] = $this->Mycommon->getCategoryAsSelect ( -1);
		}

		
			$this->load->helper('ckeditor');
			$data ['ckeditor']=$this->_initCKEditor();

		
			$data ['current_dein']='projects';
			$this->load->view ( 'admin/header_view', $data );
			$this->load->view ( 'admin/admin_project_edit_view', $data );
			$this->load->view ( 'admin/footer_view', $data );
		
	}
	/**
     * Enter description here ...
     * @param data
     */
     function _initCKEditor ()
    {
        /*********** inicialize  CKEditor *********/
		//Ckeditor's configuration
		$data  = array(
 
			//ID of the textarea that will be replaced
			'id' 	=> 	'description',
			'path'	=>	'js/ckeditor',
 
			//Optionnal values
			'config' => array(
				'toolbar' 	=> array(
	      array( 'Source', '-', 'Bold', 'Italic', 'Underline', 'Strike' )
	      //,	      array( 'Image', 'Link', 'Unlink', 'Anchor' )
	  ), 	
			//"Basic",//"Full", 	//Using the Full toolbar
				'width' 	=> 	"450px",	//Setting a custom width
				'height' 	=> 	'100px',	//Setting a custom height
                 'uiColor' => '#AACFE4',
                 'toolbarStartupExpanded' => FALSE,
		        
		        'resize_enabled'=> false,
			),
 
			//Replacing styles from the "Styles tool"
//			'styles' => array(
// 
//				//Creating a new style named "style 1"
//				'style 1' => array (
//					'name' 		=> 	'Blue Title',
//					'element' 	=> 	'h2',
//					'styles' => array(
//						'color' 	=> 	'Blue',
//						'font-weight' 	=> 	'bold'
//					)
//				),
// 
//				//Creating a new style named "style 2"
//				'style 2' => array (
//					'name' 	=> 	'Red Title',
//					'element' 	=> 	'h2',
//					'styles' => array(
//						'color' 		=> 	'Red',
//						'font-weight' 		=> 	'bold',
//						'text-decoration'	=> 	'underline'
//					)
//				)				
//			)
        
		);
		return $data;
		/*********** end CKEditor inicialization **/
    }

	
	function _checkData($data){
	    $errorTxt='';
	    if (is_null($data['title'])|| trim($data['title'])==''){
	        $errorTxt="<li>Не е въведено име</li>";
	    }
//	    if (is_null($data['category'])|| trim($data['category'])=='5'){
//	        $errorTxt.="<li>Не е избрана категория!!!</li>";
//	    }
	    
	    if ($errorTxt=='')
	        return FALSE;
	    else
	        return $errorTxt;
	}
	function save(){
	    $doUpload=$this->input->post('upload');
	    $doSave=$this->input->post('save');
	    if (!isset($doUpload) || !isset($doSave)){
	        $this->edit(null);
	        return;
	    }
	    
	    //Sabirame dannite
        $data['project']  = array('title'=>$this->input->post('title'),
//            'category'=>$this->input->post('s_category'),
			'description'=>trim($this->input->post('description'))
//        ,
//			'company'=>$this->input->post('company'),
//			'link'=>$this->input->post('link'),
//			'is_promotion'=>$this->input->post('s_promotion')
        );
//        $data['categories']=$this->Mycommon->getCategoryAsSelect ( $this->input->post('s_category'));
		
		$data ['title'] = 'Displaying user data';
		$data ['header'] = 'User List';
		$data ['projectId'] = $this->input->post('projectId');
		if ($data ['projectId']){
		    $data ['images'] = $this->ProjectsM->get_images($data ['projectId']);
		}
		
	   	if ($this->input->post('save')){
	   	    $chk=$this->_checkData($data['project']);
          if ($chk){
              $data['error']=$chk;
          }else{		    
    		   $dataSave=array(
    	            //'productId'=>$this->input->post('productId'),
    				'title'=>$this->input->post('title'),
//    				'category'=>$this->input->post('s_category'),
    				'description'=>$this->input->post('description')
//    		   ,
//    				'company'=>$this->input->post('company'),
//    				'link'=>$this->input->post('link'),
//    				'is_promotion'=>$this->input->post('s_promotion')
    				);	
    			if ($this->input->post('projectId')){
    			    $id=$this->input->post('projectId');
    				$this->db->where('id',$this->input->post('projectId'));	
    				$this->db->update('projects',$dataSave);
    			}else {
    			    $this->db->insert('projects',$dataSave);
    				$id=$this->db->insert_id();
    				$data ['projectId']=$id;
    				$this->_createDirs($id);
    				//mkdir($this->ProductsM->gallery_path . '/' . $id.'/thumbs3');
    			}
        	      $this->db->_error_message();
        	      $data['success']="Данните са записани успешно!!!";
          }
	   	}
	   	/************ UPLOAD *************/
	   	if ($this->input->post('upload')){
			$this->load->model('admin/Upload_model');
		
		//log_message('debug', 'aaa='.);
			$uploaded_file=$this->Upload_model->do_upload();
			if ($this->input->post('color')==''){
			    $data['error']='<li>Не сте въвели цвят на изображението!!!</li>';
			//    $data['error']=$_FILES['userfile']['error'];
			}else {
			   
    			$uploaded_file=array_merge($uploaded_file,array('color'=>$this->input->post('color')));
             	$this->_savePic($uploaded_file,$data ['projectId']);
             	$data ['images'] = $this->ProjectsM->get_images($data ['projectId']);   
			}
            
	   	}
	   	
	   	$this->load->helper('ckeditor');

        $data ['ckeditor']=$this->_initCKEditor();
	   	$data ['current_dein']='projects';
		$this->load->view ( 'admin/header_view', $data );
		$this->load->view ( 'admin/admin_project_edit_view', $data );
		$this->load->view ( 'admin/footer_view', $data );
	}
		
	function _savePic($newImage,$id){
	    $picture = fopen($newImage['file_path'].$newImage['new_name'],'r');
          $bytePic = fread($picture, filesize($newImage['file_path'].$newImage['new_name']));
          fclose($picture);
          $sqlpic = mysql_real_escape_string($bytePic); 
          
          $dataPic=array('id_project'=>$id,
                         'title'=>$newImage['color'],
                         'name'=>$newImage['orig_name'],
                         'pic_data'=>$sqlpic,
                         'type'=>$newImage['file_ext']);
          
          $this->db->insert('prj_pictures',$dataPic);
          rename($newImage['file_path'].$newImage['new_name']  ,
                  $this->ProjectsM->gallery_path . '/' . $id.'/'.$newImage['orig_name']);
          rename($newImage['file_path'].'/thumbs/'.$newImage['new_name']  ,
                  $this->ProjectsM->gallery_path . '/' . $id.'/thumbs/'.$newImage['orig_name']);
          rename($newImage['file_path'].'/thumbs2/'.$newImage['new_name']  ,
                  $this->ProjectsM->gallery_path . '/' . $id.'/thumbs2/'.$newImage['orig_name']);
          rename($newImage['file_path'].'thumbs3/'.$newImage['new_name']  ,
                  $this->ProjectsM->gallery_path . '/' . $id.'/thumbs3/'.$newImage['orig_name']);
	}
	
	
	/**
	 * Изтриване на картинки от базата и съответните директории
	 * @param unknown_type $forRemove
	 * @param unknown_type $id
	 */
	function removePic($value,$id){
	    $this->db->delete('prj_pictures',array('id_project'=>$id,'name'=>$value));
        unlink($this->ProjectsM->gallery_path . '/' . $id.'/'.$value);
        unlink($this->ProjectsM->gallery_path . '/' . $id.'/thumbs/'.$value);
        unlink($this->ProjectsM->gallery_path . '/' . $id.'/thumbs2/'.$value);
        unlink($this->ProjectsM->gallery_path . '/' . $id.'/thumbs3/'.$value);
        $this->edit($id);
        return;
	    
	}

     /**
      * Изтрива всичко за  избран продукт
      * @param unknown_type $id
      * @param unknown_type $page
      */
     function remove($id=null,$page=null){
         print_r($id.' '.$page);
       if (isset ( $id )) {
           $this->db->delete('prj_pictures',array('id_project'=>$id));
          $total = $this->ProjectsM->delete ($id);
          $this->Mycommon->delete_directory($this->ProjectsM->gallery_path . '/' . $id);
                   
       }
       $this->view((!is_null($page)?$page:null));
         return;
         
   }
   function _createDirs($id){
        mkdir($this->ProjectsM->gallery_path . '/' . $id);
	    mkdir($this->ProjectsM->gallery_path . '/' . $id.'/thumbs');
		mkdir($this->ProjectsM->gallery_path . '/' . $id.'/thumbs2');
		mkdir($this->ProjectsM->gallery_path . '/' . $id.'/thumbs3');
   } 
    
}

  
?>